import { onBeforeUnmount, ref } from "vue";
import { designComponent } from "src/use/designComponent";
import DemoUseEventTable,{ DemoUseEventTablePart } from "./DemoUseEventTable";

export const DemoUseEventHead = designComponent({
  setup() {
    const wrapperEl = ref<null | HTMLDivElement>(null);
    const table = DemoUseEventTable.use.inject();

    const handler = {
      scroll: (e: Event, part: DemoUseEventTablePart) => {        
        if (part === DemoUseEventTablePart.body) {
          wrapperEl.value!.scrollLeft = (e.target as HTMLDivElement).scrollLeft;
        }
      },
      wrappeScroll: (e: Event) => {
        if (table.state.hoverPart === DemoUseEventTablePart.head) {
          table.event.emit.scroll(e, DemoUseEventTablePart.head);
        }
      },
      mousewheel: (e: MouseWheelEvent) => {
        wrapperEl.value!.scrollLeft = wrapperEl.value!.scrollLeft + e.deltaY;
      }
    };
    
    table.event.on.scroll(handler.scroll);
    onBeforeUnmount(() => table.event.off.scroll(handler.scroll));

    return {
      render: () => (
        <div
          class="demo-use-event-table-head"
          ref={wrapperEl}
          onScroll={handler.wrappeScroll}
          {...{ onMousewheel: handler.mousewheel }}
        >
          <div class="demo-use-event-table-head-inner">table-head</div>
        </div>
      )
    };
  }
});
